package org.linlinjava.litemall.admin.web;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.systemConfig.SystemConfig;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@RestController
@RequestMapping("/admin/order")
public class AdminOrderController {
	private final Log logger = LogFactory.getLog(AdminOrderController.class);

	@Autowired
	private LitemallMechanismUserService litemallMechanismUserService;

	@Autowired
	private PlatformTransactionManager txManager;

	@Autowired
	private LitemallOrderGoodsService orderGoodsService;

	@Autowired
	private LitemallOrderService orderService;

	@Autowired
	private LitemallProductService productService;

	@Autowired
	private LitemallUserService userService;

	@Autowired
	private NotifyService notifyService;

	@Autowired
	private LitemallWalletRecordService walletRecordService;

	@Autowired
	private LitemallMechanismUserService mechanismUserService;

	@Autowired
	private LitemallMechanismService litemallMechanismService;

	/**
	 * 2级代理
	 */
	private static String LEVEL_TWO = "2";

	/**
	 * 3,4级代理编号
	 */
	private static ArrayList<String> ARRAY_LEVL3_LEVEL4 = new ArrayList<String>() {{
		add("3");
		add("4");
	}};

	@GetMapping("/list")
	public Object list(
		@LoginAdmin Integer adminId,
		String goodsId,
		Integer userId,
		Short value,
		String orderSn,
		String start,
		String end,
		@RequestParam(required = false) List<Short> orderStatusArray,
		@RequestParam(value = "page", defaultValue = "1") Integer page,
		@RequestParam(value = "limit", defaultValue = "10") Integer limit,
		String sort,
		String order) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		JSONArray jsonArray = new JSONArray();
		LocalDateTime localDateTime1 = null;
		LocalDateTime localDateTime2 = null;
		if (StringUtils.isNotEmpty(start) && StringUtils.isNotEmpty(end)) {
			try {
				jsonArray.add(0, Long.parseLong(start));
			}
			catch (NumberFormatException e) {
				jsonArray.add(0, start);
			}
			jsonArray.add(1, end);
			Date starts = jsonArray.getTimestamp(0);
			Date ends = jsonArray.getTimestamp(1);
			Instant instant = starts.toInstant();
			Instant instants = ends.toInstant();
			ZoneId zoneId = ZoneId.systemDefault();
			localDateTime1 = instant.atZone(zoneId).toLocalDateTime();
			localDateTime2 = instants.atZone(zoneId).toLocalDateTime();
		}

		List<Integer> orderSns = new ArrayList<>();
		if (goodsId != null) {
			Integer intGoodsId;
			try {
				intGoodsId = Integer.parseInt(goodsId);
			}
			catch (NumberFormatException e) {
				return ResponseUtil.fail(-1, "商品Id输入值不正确");
			}
			List<LitemallOrderGoods> litemallOrderGoods = orderGoodsService.queryByGoodId(intGoodsId);
			if (litemallOrderGoods.size() > 0) {
				for (LitemallOrderGoods litemallOrderGoods1 : litemallOrderGoods) {
					orderSns.add(litemallOrderGoods1.getOrderId());
				}
			}
		}
		List<LitemallOrder> orderList = orderService.querySelective(userId, orderSn, value, orderStatusArray, page, limit, sort, order, orderSns, localDateTime1, localDateTime2);
		long total = PageInfo.of(orderList).getTotal();
		Map<String, Object> data = new HashMap<>(2);
		data.put("total", total);
		data.put("items", orderList);

		return ResponseUtil.ok(data);
	}

	@GetMapping("/totalList")
	public Object totalList(
		@LoginAdmin Integer adminId,
		Integer userId,
		String goodsId,
		Short value,
		String orderSn,
		String start,
		String end,
		@RequestParam(required = false, value = "orderStatusArray[]") List<Short> orderStatusArray,
		String sort,
		String order) {
		JSONArray jsonArray = new JSONArray();
		LocalDateTime localDateTime1 = null;
		LocalDateTime localDateTime2 = null;
		if (StringUtils.isNotEmpty(start) && StringUtils.isNotEmpty(end)) {
			try {
				jsonArray.add(0, Long.parseLong(start));
			}
			catch (NumberFormatException e) {
				jsonArray.add(0, start);
			}
			jsonArray.add(1, end);
			Date starts = jsonArray.getTimestamp(0);
			Date ends = jsonArray.getTimestamp(1);
			Instant instant = starts.toInstant();
			Instant instants = ends.toInstant();
			ZoneId zoneId = ZoneId.systemDefault();
			localDateTime1 = instant.atZone(zoneId).toLocalDateTime();
			localDateTime2 = instants.atZone(zoneId).toLocalDateTime();
		}

		List<Integer> orderSns = new ArrayList<>();
		if (goodsId != null) {
			Integer intGoodsId;
			try {
				intGoodsId = Integer.parseInt(goodsId);
			}
			catch (NumberFormatException e) {
				return ResponseUtil.fail(-1, "商品Id输入值不正确");
			}
			List<LitemallOrderGoods> litemallOrderGoods = orderGoodsService.queryByGoodId(intGoodsId);
			if (litemallOrderGoods.size() > 0) {
				for (LitemallOrderGoods litemallOrderGoods1 : litemallOrderGoods) {
					orderSns.add(litemallOrderGoods1.getOrderId());
				}
			}
		}
		List<LitemallOrder> orderList = orderService.queryTotalSelective(userId, orderSn, value, orderStatusArray, sort, order, orderSns,localDateTime1,localDateTime2);
        List<Object> newList = new ArrayList<>();
        for(LitemallOrder litemallOrder:orderList){
	        newList.add(litemallOrder);
        	Integer orderId = litemallOrder.getId();
	        List<LitemallOrderGoodsExcel> orderGoods = orderGoodsService.queryInfo(orderId);
	        newList.addAll(orderGoods);
        }
		Map<String, Object> data = new HashMap<>(1);
		data.put("items", newList);

		return ResponseUtil.ok(data);
	}

	@GetMapping("/detail")
	public Object detail(@LoginAdmin Integer adminId, @NotNull Integer id) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}

		LitemallOrder order = orderService.findById(id);
		List<LitemallOrderGoods> orderGoods = orderGoodsService.queryByOid(id);
		UserVo user = null;
		LitemallMechanismUser mechanismUser = null;

		//判断是机构用户还是普通用户
		Boolean mechanismType = order.getMechanismType();

		if (mechanismType == null) {
			mechanismType = false;
		}

		if (mechanismType) {
			mechanismUser = mechanismUserService.findById(order.getUserId());
		} else {
			user = userService.findUserVoById(order.getUserId());
		}

		Map<String, Object> data = new HashMap<>(4);
		data.put("order", order);
		data.put("orderGoods", orderGoods);
		data.put("user", user);
		data.put("mechanismUser", mechanismUser);

		return ResponseUtil.ok(data);
	}

    @PostMapping("/insertRemark")
	public Object insertRemark(@LoginAdmin Integer adminId,@RequestBody String body){
	    if (adminId == null) {
		    return ResponseUtil.unlogin();
	    }
	    Integer id = JacksonUtil.parseInteger(body, "id");
	    String remark = JacksonUtil.parseString(body, "remark");
	    LitemallOrderGoods litemallOrderGoods = new LitemallOrderGoods();
	    litemallOrderGoods.setId(id);
	    litemallOrderGoods.setRemark(remark);
	    int num = orderGoodsService.updateOrderGoods(litemallOrderGoods);
	    if(num==1){
	    	return ResponseUtil.ok();
	    }else {
		    return ResponseUtil.fail();
	    }
    }
	@GetMapping("/unShipOrderNum")
	public Object queryUnShipOrderNum(@LoginAdmin Integer adminId, String status) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		int number = orderService.queryUnShipOrderNum(status);
		LocalDateTime time1 = LocalDateTime.now();
		LocalDateTime time2 = time1.minusSeconds(30);
		short statue1 = 201;
		int daiFaNum = orderService.querydaifahuoNum(statue1, time1, time2);
		Map<String, Object> data = new HashMap<>(16);
		data.put("unShipOrder", number);
		data.put("daiFaNum", daiFaNum);
		return ResponseUtil.ok(data);
	}

	/**
	 * 订单退款确认
	 * 1. 检测当前订单是否能够退款确认
	 * 2. 设置订单退款确认状态
	 * 3. 订单商品恢复
	 *
	 * @param adminId 管理员ID
	 * @param body    订单信息，{ orderId：xxx }
	 * @return 订单操作结果
	 * 成功则 { errno: 0, errmsg: '成功' }
	 * 失败则 { errno: XXX, errmsg: XXX }
	 */
	@PostMapping("refund")
	public Object refund(@LoginAdmin Integer adminId, @RequestBody String body) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		Integer orderId = JacksonUtil.parseInteger(body, "orderId");
		String recordSn = JacksonUtil.parseString(body, "recordSn");
		String refundIntegral = JacksonUtil.parseString(body, "refundIntegral");
		String refundMoney = JacksonUtil.parseString(body, "refundMoney");

		if (orderId == null) {
			return ResponseUtil.badArgument();
		}

		LitemallOrder order = orderService.findById(orderId);
		if (order == null) {
			return ResponseUtil.badArgument();
		}

		if (order.getActualPrice().compareTo(new BigDecimal(refundMoney)) != 0) {
			return ResponseUtil.badArgumentValue();
		}

		// 如果订单不是退款状态，则不能退款
		if (!order.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) {
			return ResponseUtil.fail(403, "订单不能退款");
		}

		// 开启事务管理
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);
		try {
			// 设置订单取消状态
			order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM);
			orderService.update(order);

			// 商品货品数量增加
			List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
			for (LitemallOrderGoods orderGoods : orderGoodsList) {
				Integer productId = orderGoods.getProductId();
				LitemallProduct product = productService.findById(productId);
				Integer number = product.getNumber() + orderGoods.getNumber();
				product.setNumber(number);
				productService.updateById(product);
			}

			//用户返还积分与爱币
			Integer userId = order.getUserId();
			LitemallUser user = userService.findById(userId);

			user.setBalance(user.getBalance().add(new BigDecimal(refundMoney).setScale(2, BigDecimal.ROUND_HALF_UP)));
			user.setIntegral(user.getIntegral() + Integer.valueOf(refundIntegral));
			userService.update(user);

			//钱包记录插入退款记录
			LitemallWalletRecord walletRecord = new LitemallWalletRecord();
			LocalDateTime nowDateTime = LocalDateTime.now();
			walletRecord.setUserId(userId);
			walletRecord.setRecordSn(recordSn);
			walletRecord.setType(Byte.valueOf("4"));
			walletRecord.setModifyIntegral(Integer.valueOf(refundIntegral));
			walletRecord.setModifyAmount(new BigDecimal(refundMoney).setScale(2, BigDecimal.ROUND_HALF_UP));
			walletRecord.setModifyReason("退款");
			walletRecord.setModifyTime(nowDateTime);
			walletRecord.setPayId(recordSn);
			walletRecord.setPayTime(nowDateTime);
			walletRecordService.add(walletRecord);
		}
		catch (Exception ex) {
			txManager.rollback(status);
			logger.error("系统内部错误", ex);
			return ResponseUtil.fail(403, "订单退款失败");
		}

		//TODO 发送邮件和短信通知，这里采用异步发送
		// 退款成功通知用户
		/**
		 *
		 * 您申请的订单退款 [ 单号:{1} ] 已成功，请耐心等待到账。
		 * 注意订单号只发后6位
		 *
		 */
		notifyService.notifySmsTemplate(order.getMobile(), NotifyType.REFUND, new String[] {order.getOrderSn().substring(8, 14)});

		txManager.commit(status);

		return ResponseUtil.ok();
	}

	/**
	 * 发货
	 * 1. 检测当前订单是否能够发货
	 * 2. 设置订单发货状态
	 *
	 * @param adminId 管理员ID
	 * @param body    订单信息，{ orderId：xxx, shipSn: xxx, shipChannel: xxx }
	 * @return 订单操作结果
	 * 成功则 { errno: 0, errmsg: '成功' }
	 * 失败则 { errno: XXX, errmsg: XXX }
	 */
	@PostMapping("ship")
	public Object ship(@LoginAdmin Integer adminId, @RequestBody String body) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		Integer orderId = JacksonUtil.parseInteger(body, "orderId");
		String shipSn = JacksonUtil.parseString(body, "shipSn");
		String shipChannel = JacksonUtil.parseString(body, "shipChannel");
		if (orderId == null || shipSn == null || shipChannel == null) {
			return ResponseUtil.badArgument();
		}

		LitemallOrder order = orderService.findById(orderId);
		if (order == null) {
			return ResponseUtil.badArgument();
		}

		// 如果订单不是已付款状态，则不能发货
		if (!order.getOrderStatus().equals(OrderUtil.STATUS_PAY)) {
			return ResponseUtil.fail(403, "订单不能确认收货");
		}

		order.setOrderStatus(OrderUtil.STATUS_SHIP);
		order.setShipSn(shipSn);
		order.setShipChannel(shipChannel);
		order.setShipTime(LocalDateTime.now());
		orderService.update(order);

		//TODO 发送邮件和短信通知，这里采用异步发送
		// 发货会发送通知短信给用户
		/**
		 *
		 * 您的订单已经发货，快递公司 {1}，快递单 {2} ，请注意查收
		 *
		 */
		notifyService.notifySmsTemplate(order.getMobile(), NotifyType.SHIP, new String[] {shipChannel, shipSn});

		return ResponseUtil.ok();
	}

	/**
	 * 自动取消订单
	 * <p>
	 * 定时检查订单未付款情况，如果超时半个小时则自动取消订单
	 * 定时时间是每次相隔半个小时。
	 * <p>
	 * 注意，因为是相隔半小时检查，因此导致有订单是超时一个小时以后才设置取消状态。
	 * TODO
	 * 这里可以进一步地配合用户订单查询时订单未付款检查，如果订单超时半小时则取消。
	 */
	@Scheduled(fixedDelay = 30 * 60 * 1000)
	public void checkOrderUnpaid() {
		logger.debug(LocalDateTime.now());

		List<LitemallOrder> orderList = orderService.queryUnpaid();
		for (LitemallOrder order : orderList) {
			LocalDateTime add = order.getAddTime();
			LocalDateTime now = LocalDateTime.now();
			LocalDateTime expired = add.plusMinutes(30);
			if (expired.isAfter(now)) {
				continue;
			}

			// 开启事务管理
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
			TransactionStatus status = txManager.getTransaction(def);
			try {
				// 设置订单已取消状态
				order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
				order.setEndTime(LocalDateTime.now());
				orderService.updateById(order);

				// 商品货品数量增加
				Integer orderId = order.getId();
				List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
				for (LitemallOrderGoods orderGoods : orderGoodsList) {
					Integer productId = orderGoods.getProductId();
					LitemallProduct product = productService.findById(productId);
					Integer number = product.getNumber() + orderGoods.getNumber();
					product.setNumber(number);
					productService.updateById(product);
				}
			}
			catch (Exception ex) {
				txManager.rollback(status);
				logger.error("系统内部错误", ex);
			}
			txManager.commit(status);
		}
	}

	/**
	 * 自动确认订单
	 * <p>
	 * 定时检查订单未确认情况，如果超时七天则自动确认订单
	 * 定时时间是每天凌晨3点。
	 * <p>
	 * 注意，因为是相隔一天检查，因此导致有订单是超时八天以后才设置自动确认。
	 * 这里可以进一步地配合用户订单查询时订单未确认检查，如果订单超时7天则自动确认。
	 * 但是，这里可能不是非常必要。相比订单未付款检查中存在商品资源有限所以应该
	 * 早点清理未付款情况，这里八天再确认是可以的。
	 * <p>
	 * TODO
	 * 目前自动确认是基于管理后台管理员所设置的商品快递时间，见orderService.queryUnconfirm。
	 * 那么在实际业务上有可能存在商品寄出以后商品因为一些原因快递最终没有到达，
	 * 也就是商品快递失败而shipEndTime一直是空的情况，因此这里业务可能需要扩展，以防止订单一直
	 * 处于发货状态。
	 * <p>
	 * 检查过期的会员，将会员标志设为false,并删除过期日期
	 * </p>
	 */
	@Scheduled(cron = "0 0 3 * * ?")
	public void checkOrderUnconfirm() {
		logger.debug(LocalDateTime.now());

		//删除微信过期会员
		List<LitemallUser> users = userService.queryEndUser(LocalDateTime.now());
		if (users.size() > 0) {
			for (LitemallUser litemallUser : users) {
				litemallUser.setMemberType(false);
				userService.update(litemallUser);
			}
		}

		//删除机构过期会员
		//		List<LitemallMechanism> mechanisms = litemallMechanismService.queryEndUser(LocalDateTime.now());
		//		if (mechanisms.size() > 0) {
		//			for (LitemallMechanism litemallMechanism : mechanisms) {
		//				litemallMechanism.setDeleted(true);
		//				litemallMechanismService.updateById(litemallMechanism);
		//			}
		//		}

		//自动收货
		List<LitemallOrder> orderList = orderService.queryUnconfirm();
		for (LitemallOrder order : orderList) {
			LocalDateTime ship = order.getShipTime();
			LocalDateTime now = LocalDateTime.now();
			LocalDateTime expired = ship.plusDays(7);
			if (expired.isAfter(now)) {
				continue;
			}
			LitemallUser user = userService.findById(order.getUserId());
			// 设置订单已取消状态
			order.setOrderStatus(OrderUtil.STATUS_AUTO_CONFIRM);
			order.setConfirmTime(now);
			// 开启事务管理
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
			TransactionStatus status = txManager.getTransaction(def);
			try {
				orderService.updateById(order);
				Integer giveIntegral = order.getGiveIntegral();
				BigDecimal givePrice = order.getGivePrice();
				BigDecimal giveBalance = order.getGiveBalance();

				if (giveIntegral != 0 || givePrice.compareTo(new BigDecimal(0.00)) != 0) {
					//存在返还的积分或者爱币
					//返还到用户钱包
					user.setIntegral(user.getIntegral() + giveIntegral);
					user.setBalance(user.getBalance().add(givePrice));
					userService.update(user);
					//添加钱包的记录
					LitemallWalletRecord walletRecord = new LitemallWalletRecord();
					LocalDateTime nowTime = LocalDateTime.now();
					String recordSn = this.createRecordSn();
					walletRecord.setUserId(order.getUserId());
					walletRecord.setRecordSn(recordSn);
					walletRecord.setType(new Byte("5"));
					walletRecord.setModifyAmount(givePrice);
					walletRecord.setModifyIntegral(giveIntegral);
					walletRecord.setPayId(recordSn);
					walletRecord.setPayTime(nowTime);
					walletRecord.setModifyTime(nowTime);
					walletRecord.setModifyReason("消费返赠");
					walletRecordService.add(walletRecord);
				}
				if (giveBalance.compareTo(new BigDecimal(0)) != 0 && giveBalance != null) {
					if (user.getFirstMechanism() != null) {
						//用户所在的机构的登录人员下的账号
						LitemallMechanismUser mechanismUser = litemallMechanismUserService.queryByMechanismId(user.getFirstMechanism());
						//用户所在的机构
						LitemallMechanism litemallMechanism = litemallMechanismService.findById(user.getFirstMechanism());
						//1 如果此机构的等级为2 有代理 代理机构获取2%
						if (litemallMechanism.getLevel() != null && LEVEL_TWO.equals(litemallMechanism.getLevel().toString())) {
							//并且代理归属的等级为3或4 ，将2%的交易额返还给代理归属机构下用户的账户
							if (litemallMechanism.getAffiliation() != null) {
								LitemallMechanism litemallMechanism1 = litemallMechanismService.findValid(litemallMechanism.getAffiliation());
								if (litemallMechanism1 !=null && ARRAY_LEVL3_LEVEL4.contains(litemallMechanism1.getLevel().toString())) {
									//获取代理归属的人员账号，将金额打入这个账号，并且添加钱包记录
									LitemallMechanismUser litemallMechanismUser = litemallMechanismUserService.queryByMechanismId(litemallMechanism1.getId());
									if (litemallMechanismUser != null) {
										if (litemallMechanismUser.getBalance() == null) {
											litemallMechanismUser.setBalance(giveBalance);
										} else {
											litemallMechanismUser.setBalance(litemallMechanismUser.getBalance().add(giveBalance));
										}
										litemallMechanismUserService.update(litemallMechanismUser);
									}
									LitemallWalletRecord meWalletRecord1 = new LitemallWalletRecord();
									meWalletRecord1.setMechaismId(litemallMechanismUser.getId());
									meWalletRecord1.setModifyAmount(giveBalance);
									meWalletRecord1.setModifyTime(LocalDateTime.now());
									meWalletRecord1.setModifyReason("子机构会员购买会员商品返利");
									meWalletRecord1.setType(new Byte("5"));
									walletRecordService.add(meWalletRecord1);
								}
							}
						}

						//2 如果此机构的等级大于2，查看是否是新代理 ，如果是，通过用户是否是新会员 如果是 ，则将2%返给本机构。不返给代理
						//                                       如果不是，则返给机构和代理
						if (litemallMechanism.getLevel() != null && ARRAY_LEVL3_LEVEL4.contains(litemallMechanism.getLevel().toString())) {
							// 是新代理 查看用户是不是新会员
							if (litemallMechanism.getNewProxyFlag()) {
								if (user.getNewProxyFlag()) {
									// 不用返给代理机构了
								} else {
									// 返给代理机构
									if (litemallMechanism.getAffiliation() != null) {
										LitemallMechanism litemallMechanism1 = litemallMechanismService.findValid(litemallMechanism.getAffiliation());
										if (litemallMechanism1 !=null && ARRAY_LEVL3_LEVEL4.contains(litemallMechanism1.getLevel().toString())) {
											//获取代理归属的人员账号，将金额打入这个账号，并且添加钱包记录
											LitemallMechanismUser litemallMechanismUser = litemallMechanismUserService.queryByMechanismId(litemallMechanism1.getId());
											if (litemallMechanismUser != null) {
												if (litemallMechanismUser.getBalance() == null) {
													litemallMechanismUser.setBalance(giveBalance);
												} else {
													litemallMechanismUser.setBalance(litemallMechanismUser.getBalance().add(giveBalance));
												}
												litemallMechanismUserService.update(litemallMechanismUser);
											}
											LitemallWalletRecord meWalletRecord1 = new LitemallWalletRecord();
											meWalletRecord1.setMechaismId(litemallMechanismUser.getId());
											meWalletRecord1.setModifyAmount(giveBalance);
											meWalletRecord1.setModifyTime(LocalDateTime.now());
											meWalletRecord1.setModifyReason("子机构会员购买会员商品返利");
											meWalletRecord1.setType(new Byte("5"));
											walletRecordService.add(meWalletRecord1);
										}
									}
								}
							} else {
								// 老代理（原机构等级就是3或4），是老用户 就返代理2%
								if(!user.getNewProxyFlag()){
									if (litemallMechanism.getAffiliation() != null) {
										LitemallMechanism litemallMechanism1 = litemallMechanismService.findValid(litemallMechanism.getAffiliation());
										if (litemallMechanism1 !=null && ARRAY_LEVL3_LEVEL4.contains(litemallMechanism1.getLevel().toString())) {
											//获取代理归属的人员账号，将金额打入这个账号，并且添加钱包记录
											LitemallMechanismUser litemallMechanismUser = litemallMechanismUserService.queryByMechanismId(litemallMechanism1.getId());
											if (litemallMechanismUser != null) {
												if (litemallMechanismUser.getBalance() == null) {
													litemallMechanismUser.setBalance(giveBalance);
												} else {
													litemallMechanismUser.setBalance(litemallMechanismUser.getBalance().add(giveBalance));
												}
												litemallMechanismUserService.update(litemallMechanismUser);
											}
											LitemallWalletRecord meWalletRecord1 = new LitemallWalletRecord();
											meWalletRecord1.setMechaismId(litemallMechanismUser.getId());
											meWalletRecord1.setModifyAmount(giveBalance);
											meWalletRecord1.setModifyTime(LocalDateTime.now());
											meWalletRecord1.setModifyReason("子机构会员购买会员商品返利");
											meWalletRecord1.setType(new Byte("5"));
											walletRecordService.add(meWalletRecord1);
										}
									}
								}
							}
						}

						// 机构得到返 2%
						LitemallWalletRecord meWalletRecord = new LitemallWalletRecord();
						if (mechanismUser != null) {
							if (mechanismUser.getBalance() == null) {
								mechanismUser.setBalance(giveBalance);
							} else {
								mechanismUser.setBalance(mechanismUser.getBalance().add(giveBalance));
							}
							litemallMechanismUserService.update(mechanismUser);
							//添加机构的钱包记录
							meWalletRecord.setMechaismId(mechanismUser.getId());
							meWalletRecord.setModifyAmount(giveBalance);
							meWalletRecord.setModifyTime(LocalDateTime.now());
							meWalletRecord.setModifyReason("会员用户购买商品");
							meWalletRecord.setType(new Byte("5"));
							walletRecordService.add(meWalletRecord);
						} else {
							//添加爱联的钱包记录
							meWalletRecord.setMechaismId(SystemConfig.getAiLianNum());
							meWalletRecord.setModifyAmount(giveBalance);
							meWalletRecord.setType(new Byte("5"));
							meWalletRecord.setModifyReason("会员用户购买商品");
							meWalletRecord.setModifyTime(LocalDateTime.now());
							walletRecordService.add(meWalletRecord);

							//爱联账户加钱
							LitemallMechanismUser aiLianMechanismUser = litemallMechanismUserService.findById(SystemConfig.getAiLianNum());
							if (aiLianMechanismUser.getBalance() == null) {
								aiLianMechanismUser.setBalance(giveBalance);
							} else {
								aiLianMechanismUser.setBalance(aiLianMechanismUser.getBalance().add(giveBalance));
							}
							litemallMechanismUserService.update(aiLianMechanismUser);

						}
					}
				}
			}
			catch (Exception ex) {
				txManager.rollback(status);
				ex.printStackTrace();
			}
			txManager.commit(status);

		}
	}

	private String createRecordSn() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String dateStr = sdf.format(date);
		String res = (int)Math.ceil(Math.random() * 1000) + "";
		return dateStr + res;
	}

}
